package com.minidota.impl;

import com.minidota.constant.ConstantTable;
import com.minidota.db.Connector;
import com.minidota.db.Db;
import com.minidota.model.HeroModel;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.util.ArrayList;

/**
 *
 * @author Fedor, Max
 */
public class HeroesImpl {
    
    private static HeroesImpl instance = HeroesImpl.getInstance();
    
    public static HeroesImpl getInstance() {
        if (instance == null) {
            instance = new HeroesImpl();
        }
        return instance;
    }
    /**
     * PREFIX для того, что бы не произошло совпадения имён
     */
    private static final String GET_HEROES = "SELECT * FROM heroes";
    
    public static ArrayList<HeroModel> getStaticTable() {
        ArrayList<HeroModel> res = new ArrayList<HeroModel>();
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = Connector.getConnection();
            try {
                ps = connection.prepareStatement(GET_HEROES);
                rs = ps.executeQuery();
                while (rs.next()) {
                    res.add(getByRs(rs));
                }
            } catch (SQLException e) {
                System.out.println("SQLException: " + e + " sql: " + GET_HEROES);
            } finally {
                Db.closeConnection(connection, ps, rs);
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        return res;
    }

    //Получить копию данных для героя из констант
    public static HeroModel getHeroByID(int id) {
        HeroModel res = null;
        for (HeroModel h : ConstantTable.getHeroesList()) {
            if (id == h.getId()) {
                return h.clone();
            }
        }
        return res;
    }
    
    public static HeroModel getByRs(ResultSet rs) throws SQLException {
        HeroModel obj = new HeroModel();
        obj.setId(rs.getInt("id"));
        obj.setTypeId(rs.getInt("type_id"));
        obj.setName(rs.getString("name"));
        obj.setDir(rs.getString("dir"));
        obj.setStrength(rs.getInt("strength"));
        obj.setAgility(rs.getInt("agility"));
        obj.setIntelligence(rs.getInt("intelligence"));
        obj.setAddStrength(rs.getInt("add_strength"));
        obj.setAddAgility(rs.getInt("add_agility"));
        obj.setAddIntelligence(rs.getInt("add_intelligence"));
        obj.setHP(rs.getInt("hp"));
        obj.setMP(rs.getInt("mp"));
        obj.setDamage(rs.getInt("damage"));
        obj.setArmor(rs.getInt("armor"));
        obj.setTicksBetweanAttack(rs.getDouble("ticks_betwean_attack"));
        obj.setMoveSpeed(rs.getInt("move_speed"));
        obj.setAtackRadius(rs.getInt("atack_radius"));
        obj.setArrowSpeed(rs.getInt("arrow_speed"));
        return obj;
    }
}
